package order

import (
	"context"
	"fmt"

	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"
	"oil-station-backend/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetOrderDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetOrderDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderDetailLogic {
	return &GetOrderDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetOrderDetailLogic) GetOrderDetail(id int64) (resp *types.Order, err error) {
	// 从上下文中获取用户ID和角色
	userId, role, err := l.getUserInfoFromContext()
	if err != nil {
		return nil, err
	}

	// 获取订单详情
	order, err := l.svcCtx.OrderModel.FindById(id)
	if err != nil {
		return nil, fmt.Errorf("订单不存在")
	}

	// 检查权限：只有管理员或订单所有者可以查看订单详情
	if role != "admin" && order.UserId != userId {
		return nil, fmt.Errorf("无权查看此订单")
	}

	// 转换为API响应格式
	var completeTime string
	if order.CompleteTime != nil {
		completeTime = order.CompleteTime.Format("2006-01-02 15:04:05")
	}

	var actualVolume, actualAmount float64
	if order.ActualVolume != nil {
		actualVolume = *order.ActualVolume
	}
	if order.ActualAmount != nil {
		actualAmount = *order.ActualAmount
	}

	return &types.Order{
		Id:            order.Id,
		OrderNo:       order.OrderNo,
		UserId:        order.UserId,
		UserName:      order.UserName,
		FuelType:      order.FuelType,
		FuelPrice:     order.FuelPrice,
		Volume:        order.Volume,
		PrepaidAmount: order.PrepaidAmount,
		ActualVolume:  actualVolume,
		ActualAmount:  actualAmount,
		Status:        order.Status,
		CreateTime:    order.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    order.UpdateTime.Format("2006-01-02 15:04:05"),
		CompleteTime:  completeTime,
	}, nil
}

func (l *GetOrderDetailLogic) getUserInfoFromContext() (int64, string, error) {
	// 使用通用工具函数获取用户信息
	return utils.GetUserInfoFromContext(l.ctx)
}